package cn.jxau.fukin.controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.jxau.fukin.model.Feedback;
import cn.jxau.fukin.model.User;
import cn.jxau.fukin.service.IFeedbackService;
import cn.jxau.fukin.service.IUserService;
import cn.jxau.fukin.util.CommonUtils;
import cn.jxau.fukin.util.PKUtil;

@Controller
@RequestMapping(value = "/feedback")
public class FeedbackController {

	@Autowired
	IUserService userService;
	@Autowired
	IFeedbackService feedbackService;

	@RequestMapping(value = "/showFeedbackPage.do")
	public String showFeedbackPage(HttpServletRequest request) {
		String flag = (String) request.getSession().getAttribute("flag");
		if (flag != null) {
			return "forward:/WEB-INF/jsp/feedback.jsp";
		} else {
			return "forward:/user/showLoginPage.do";

		}
	}

	@RequestMapping(value = "/feedback.do")
	public ModelAndView feedback(ModelAndView mv, HttpServletRequest request, Feedback feedback,
			MultipartFile picture) throws IllegalStateException, IOException {

		System.out.println(feedback);

		if (picture != null && picture.getOriginalFilename().trim() != "") {

			String filename = picture.getOriginalFilename();
			System.out.println(filename);
			String path = CommonUtils.getValueOfProprties("imageUploadPath");
			String newFileName = UUID.randomUUID()
					+ filename.substring(filename.lastIndexOf(".jpg"));

			File file = new File(path + newFileName);
			if (!file.exists()) {
				file.mkdirs();
			}
			picture.transferTo(file);
		}

		User user = (User) request.getSession().getAttribute("user");
		User newUser = userService.queryUserInfo(user).get(0);
		System.out.println("newUser=" + newUser);
		feedback.setuId(newUser.getuId());
		feedback.setuName(newUser.getuName());
		feedback.setfId(PKUtil.PrimaryKey());
		System.out.println("feedback=" + feedback);
		feedbackService.insertFeedBack(feedback);
		request.getSession().setAttribute("feedbackMsg", "反馈成功");
		mv.setViewName("redirect:/feedback/showFeedbackPage.do");
		return mv;
	}
}
